<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
use PHPImageWorkshop\ImageWorkshop;

class Image_workshop
{
    var $CI;
    var $error = false;
    var $site_url;
    var $positions = array('LT', 'MT', 'RT', 'LM', 'MM', 'RM', 'LB', 'MB', 'RB');
    var $quality = 75;
    var $base_path_return = false;


    public function __construct()
    {
        $this->CI = & get_instance();
        require_once(APPPATH . '/libraries/PHPImageWorkshop/Exception/ImageWorkshopBaseException.php');
        require_once(APPPATH . '/libraries/PHPImageWorkshop/Exception/ImageWorkshopException.php');
        require_once(APPPATH . '/libraries/PHPImageWorkshop/Core/Exception/ImageWorkshopLayerException.php');
        require_once(APPPATH . '/libraries/PHPImageWorkshop/Core/ImageWorkshopLib.php');
        require_once(APPPATH . '/libraries/PHPImageWorkshop/Core/ImageWorkshopLayer.php');
        require_once(APPPATH . '/libraries/PHPImageWorkshop/ImageWorkshop.php');
        $this->site_url = $this->CI->config->SCRIPT_NAME;
        $this->quality = $this->CI->config->item('image_quality');
    }

    public function crop_image($img_path, $width, $height, $position, $cache_folder = false, $false_return = false)
    {
        if (!$img_path || ($img_path && !file_exists($img_path))) {
            if (!$false_return) {
                $img_path = NO_IMAGE_LINK;
            } else {
                return false;
            }
        }
        if (!$position || ($position && !in_array($position, $this->positions)))
            $position = 'MM';
        $width = (int)$width;
        $height = (int)$height;
        $pathInfo = pathinfo($img_path);
        $cache_name = $pathInfo['filename'] . '-' . $width . 'x' . $height . '-' . $position . '-' . $this->quality . '.' . $pathInfo['extension'];
        $cache_folder = MAIN_CACHE_PATH . '/' . abs(crc32(trim($cache_folder, DS) . DS . $pathInfo['dirname']));
        $full_cache_path = $cache_folder . '/' . $cache_name;
        if (file_exists(FCPATH . $full_cache_path)) {
            if ($this->base_path_return)
                return $full_cache_path;
            return $this->site_url . $full_cache_path;
        }
        $convert = false;
        try {
            $layer = ImageWorkshop::initFromPath(FCPATH . $img_path);
            if ($height) {
                $calc_image_res = calc_image_res($width, $height, $layer->getWidth(), $layer->getHeight());
                $layer->resizeInPixel($calc_image_res['width'], $calc_image_res['height'], TRUE, 0, 0, $position);
                $layer->cropInPixel($width, $height, 0, 0, $position);
            } else {
                $layer->resizeInPixel($width, null, true);
            }
            $layer->save($cache_folder, $cache_name, true, NULL, $this->quality, true);
            $convert = true;
        } catch (Exception $e) {
            log_message('error', $e->getMessage());
            $this->error = $e->getMessage();
            $convert = false;
        }
        if (!$convert)
            return false;
        if ($this->base_path_return)
            return $full_cache_path;
        return $this->site_url . $full_cache_path;
    }


    public function resize_and_move($temp_file, $move_folder, $move_fileName, $width, $height, $position = 'MM')
    {
        $convert = false;
        try {
            $layer = ImageWorkshop::initFromPath(FCPATH . $temp_file);
            $calc_image_res = calc_image_res($width, $height, $layer->getWidth(), $layer->getHeight());
            $layer->resizeInPixel($calc_image_res['width'], $calc_image_res['height'], TRUE, 0, 0, $position);
            $layer->cropInPixel($width, $height, 0, 0, $position);
            $layer->save($move_folder, $move_fileName, true, NULL, $this->quality, true);
            $convert = true;
            @unlink(FCPATH . $temp_file);
        } catch (Exception $e) {
            log_message('error', $e->getMessage());
            $this->error = $e->getMessage();
            $convert = false;
        }
        return $convert;
    }

    public function convert_resolution($original_image, $hash, $date, $width, $height, $position = 'MM', $path_return = false)
    {
        if (!$original_image || ($original_image && !file_exists(ORIGINALS_FOLDER . DS . $original_image))) {
            return false;
        }
        if (!$position || ($position && !in_array($position, $this->positions)))
            $position = 'MM';
        $width = (int)$width;
        $height = (int)$height;
        $cache_folder = CONVERTED_FOLDER . DS . date('y/m/d', strtotime($date));
        $pathinfo = pathinfo($original_image);

        $cache_name = abs(crc32($original_image)) . '-' . $pathinfo['filename'] . '-' . $hash . '-' . $width . 'x' . $height . '-' . $position . '-' . $this->quality . '.jpg';

        $full_cache_path = $cache_folder . '/' . $cache_name;

        if (file_exists(FCPATH . $full_cache_path)) {
            if ($path_return)
                return FCPATH . $full_cache_path;
            return $this->clean_url_path($this->site_url . $full_cache_path);
        }
        $convert = false;
        try {
            $layer = ImageWorkshop::initFromPath(FCPATH . ORIGINALS_FOLDER_WF . DS . $original_image);
            $calc_image_res = calc_image_res($width, $height, $layer->getWidth(), $layer->getHeight());
            $layer->resizeInPixel($calc_image_res['width'], $calc_image_res['height'], TRUE, 0, 0, $position);
            $layer->cropInPixel($width, $height, 0, 0, $position);
            $layer->save($cache_folder, $cache_name, true, NULL, $this->quality, true);
            $convert = true;
        } catch (Exception $e) {
            log_message('error', $e->getMessage());
            $this->error = $e->getMessage();
            $convert = false;
        }
        if (!$convert)
            return false;
        if ($path_return)
            return FCPATH . $full_cache_path;
        return $this->clean_url_path($this->site_url . $full_cache_path);
    }


    public function move_file($path, $destination, $inc_limit = 100)
    {
        if (!file_exists($destination)) {
            rename($path, $destination);
            return basename($destination);
        }
        $pathinfo = pathinfo($destination);
        $dir_name = $pathinfo['dirname'];
        $filename = $pathinfo['filename'];
        $new_filename = '';
        for ($i = 1; $i < $inc_limit; $i++) {
            if (!file_exists($dir_name . DS . $filename . $i . '.' . $pathinfo['extension'])) {
                $new_filename = $filename . $i . '.' . $pathinfo['extension'];
                break;
            }
        }
        if (!$new_filename)
            $new_filename = $filename . uniqid() . '.' . $pathinfo['extension'];
        rename($path, $dir_name . DS . $new_filename);
        return $new_filename;
    }

    private function clean_url_path($str)
    {
        return str_replace('\\', '/', $str);
    }
}
